package com.njupt.towerssystem.services.impl;

import com.njupt.towerssystem.domain.ManagerInfos;
import com.njupt.towerssystem.mapper.ManageInfoMapper;
import com.njupt.towerssystem.services.ManageService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.UUID;

@Service
public class ManageServiceImpl implements ManageService {
    @Resource
    private ManageInfoMapper manageInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ManagerInfos login(String loginname, String loginpwd, String token) {
        ManagerInfos mi = ManagerInfos.builder().loginname(loginname)
                .loginpwd(loginpwd).build();
        if (loginname != null) {
            Object res = stringRedisTemplate.opsForHash().get("mananges", loginname+loginpwd);
            if (res != null) {

                // 生成唯一令牌
                String tk = UUID.randomUUID().toString().replaceAll("-","");
                //将令牌存放到redis数据库中 让令牌保存30秒
                stringRedisTemplate.opsForValue().set(tk,loginname+loginpwd, Duration.ofMinutes(30+(long)Math.random()*100));
                // 找到对应用户
                String[] infos = res.toString().split(",");
                ManagerInfos mis = ManagerInfos.builder()
                        .userid(Integer.parseInt(infos[0]))
                        .username(infos[1])
                        .loginpwd(infos[2])
                        .tel(infos[3])
                        .department(infos[5])
                        .token(tk)
                        .build();
                return mis;
            } else {
                return null;
            }
        } else {
            // 验证用户传入的token 查看是否存在
            String res = stringRedisTemplate.opsForValue().get(token);
            if (res!=null) {
                // 令牌存在，按照令牌的key取loginname+loginpwd
                Object obj = stringRedisTemplate.opsForHash().get("mananges", res);
                String[] infos = obj.toString().split(",");
                ManagerInfos mis = ManagerInfos.builder()
                        .userid(Integer.parseInt(infos[0]))
                        .username(infos[1])
                        .loginpwd(infos[2])
                        .tel(infos[3])
                        .department(infos[5])
                        .token(token)
                        .build();
                return mis;
            }else {
                return null;
            }
        }
    }

}
